package utils

import (
	"net/http"
	"net/url"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Status uint
	Data   interface{}
	Msg    string
}

// 成功的相应
func (r *Response) SuccessResponse() gin.H {
	response := gin.H{
		"status": 0,
		"data":   r.Data,
		"msg":    "",
	}
	return response
}

// 失败的响应
func (r *Response) FailedResponse() gin.H {
	response := gin.H{
		"status": r.Status,
		"data":   r.Data,
		"msg":    r.Msg,
	}

	return response
}

// redirect 重定向
func Redirect(c *gin.Context, location string) {
	c.Redirect(http.StatusFound, location)
}

// RedirectBack 重定向到上一次的页面
func RedirectBack(c *gin.Context) {
	referer := c.GetHeader("Referer") //获取请求头中的Referer字段
	pathInfo := ""
	if referer == "" { //若referer字段为空，则证明没有上次的url，直接返回根路径
		pathInfo = "/"
	} else {
		u, _ := url.Parse(referer) //解析referer字段，获取上次的url
		pathInfo = u.Path
	}

	c.Redirect(http.StatusFound, pathInfo)
}
